package com.party.admin.web.controller.moneyManagement;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.admin.web.dto.AjaxResult;
import com.party.common.paging.Page;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.BaseModel;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.crowdfund.MemberWithdrawalFund;
import com.party.core.model.crowdfund.ProjectAnalyze;
import com.party.core.model.member.MemberBank;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.MemberGroupInfo;
import com.party.core.model.order.OrderForm;
import com.party.core.model.order.OrderStatus;
import com.party.core.model.order.OrderType;
import com.party.core.model.partner.MemberPartner;
import com.party.core.model.wallet.*;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IMemberWithdrawalFundService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.member.IMemberBankService;
import com.party.core.service.member.IMemberGroupInfoService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.partner.IMemberPartnerService;
import com.party.core.service.wallet.IWithdrawalAuditOperateService;
import com.party.core.service.wallet.IWithdrawalService;
import com.party.core.service.wallet.biz.WithdrawalsBizService;
import com.party.admin.biz.moneyManagement.MoneyManagementBizService;
import com.party.admin.biz.order.OrderBizService;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.output.order.OrderFormOutput;
import com.party.admin.web.dto.output.wallet.WithdrawalOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资金管理
 * Created by hqh
 *
 * @date 2018/11/08 0014
 * @time 16:56
 */
@Controller
@RequestMapping(value = "moneyManagement")
public class MoneyManagementController {

    @Autowired
    private OrderBizService orderBizService;

    @Autowired
    private IWithdrawalService withdrawalService;

    @Autowired
    private WithdrawalsBizService withdrawalsBizService;

    @Autowired
    private IMemberWithdrawalFundService memberWithdrawalFundService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private ICrowdfundEventService crowdfundEventService;

    @Autowired
    private IMemberBankService memberBankService;

    @Autowired
    private MoneyManagementBizService moneyManagementBizService;

    @Autowired
    private IMemberPartnerService memberPartnerService;

    @Autowired
    private IMemberGroupInfoService memberGroupInfoService;

    @Autowired
    private IWithdrawalAuditOperateService withdrawalAuditOperateService;

    @Autowired
    private IMemberGroupService memberGroupService;

    protected static Logger logger = LoggerFactory.getLogger(MoneyManagementController.class);

    /**
     * 资金管理 全部资金
     *
     * @return
     */
    @RequestMapping(value = "allMoneyList")
    public ModelAndView allMoneyList(Page page, OrderForm orderForm, CommonInput input, Integer stype, String memberId) {
        ModelAndView mv = new ModelAndView("moneyManagement/allMoneyList");
        page.setLimit(15);


        boolean isBand = true;


        if (StringUtils.isNotBlank(memberId)) {
            //选择菜单
            stype = stype == null ? 0 : stype;

            if (0 == stype) {
                input.setIsDate(1);
                Map<String, Object> params = CommonInput.appendParams(input);
                List<OrderFormOutput> orderFormOutputs = orderBizService.memberOrderList(page, orderForm, params, memberId, input.getMemberName());

                Map<Integer, String> orderTypes = Maps.newHashMap();
                orderTypes.put(OrderType.ORDER_ACTIVITY.getCode(), OrderType.ORDER_ACTIVITY.getValue());
                orderTypes.put(OrderType.ORDER_CROWD_FUND.getCode(), OrderType.ORDER_CROWD_FUND.getValue());
                orderTypes.put(OrderType.ORDER_MULTIPLE_CROWD_FUND.getCode(), OrderType.ORDER_MULTIPLE_CROWD_FUND.getValue());

                mv.addObject("orderForms", orderFormOutputs);
                mv.addObject("orderTypes", orderTypes);
            } else if (1 == stype) {
                String currentId = memberId;
                Withdrawals withdrawal = new Withdrawals();
                withdrawal.setCreateBy(currentId);
                withdrawal.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                withdrawal.setType(Withdrawals.TYPE_CROWD_FUNDING); // 余额
                List<Withdrawals> withdrawals = withdrawalService.listPage(withdrawal, page);
                List<WithdrawalOutput> withdrawalOutputs = LangUtils.transform(withdrawals, inp -> {
                    WithdrawalOutput output = WithdrawalOutput.transform(inp);
                    String account = inp.getAccountNumber();
                    account = withdrawalsBizService.formatAccountNumber(account);
                    output.setAccountNumber(account);

                    Double withdrawalCharge = inp.getWithdrawalCharge();
                    withdrawalCharge = withdrawalCharge == null ? 0d : withdrawalCharge;

                    //提现金额X（平台提现手续费+微信提现手续费）
                    double serviceFee = BigDecimalUtils.mul(inp.getPayment(), Withdrawals.SERVER_FEE + withdrawalCharge);
                    // 净额
                    double netAmount = BigDecimalUtils.sub(inp.getPayment(), serviceFee);

                    output.setServiceFee(serviceFee);
                    output.setNetAmount(netAmount);
                    return output;
                });


                // 提现总额
                Double withdrawalTotal = withdrawalsBizService.getWithdrawalTotal(currentId, Withdrawals.TYPE_CROWD_FUNDING, null);

                withdrawalTotal = withdrawalTotal == null ? 0d : withdrawalTotal;

                mv.addObject("withdrawals", withdrawalOutputs);
                mv.addObject("withdrawalTotal", withdrawalTotal);
            }

            // 累计资金
            Double orderTotal = orderBizService.getOrderTotal(false, memberId, orderForm.getType(), null);

            if (orderTotal != null) {
                mv.addObject("orderTotal", orderTotal);
            } else {
                mv.addObject("orderTotal", 0);
            }


            Map<String, Object> resultParams = orderBizService.memberInfoBiz(memberId);
            mv.addAllObjects(resultParams);
        }


        mv.addObject("input", input);
        mv.addObject("stype", stype);


        mv.addObject("page", page);
        mv.addObject("isBand", isBand);
        mv.addObject("memberId", memberId);


        boolean isChildAccount = false;
        String partnerId = null;
        MemberGroup memberGroup = memberGroupService.get(memberId);
        if (StringUtils.isNotEmpty(memberGroup.getPartnerId())) {
            isChildAccount = true;
            partnerId = memberGroup.getPartnerId();
        }

        mv.addObject("isChildAccount", isChildAccount);
        mv.addObject("partnerId", partnerId);
        mv.addObject("memberName", memberGroup.getRealname());
        return mv;
    }


    /**
     * 资金管理 众筹资金
     *
     * @return
     */
    @RequestMapping(value = "crowdFundingMoneyList")
    public ModelAndView crowdFundingMoneyList(Page page, String memberId) {
        ModelAndView mv = new ModelAndView("moneyManagement/crowdFundingMoneyList");
        page.setLimit(15);

        //众筹累计资金
        Double orderTotal = 0d;
        //总可提现金额0
        Double totalAleAmount = 0d;
        //已提现金额
        Double edWithdrawalsAmount = 0d;
        //当前可提现金额
        Double ingWithdrawalsAmount = 0d;

        List<CrowdfundEventWithdrawalsOutput> cewoLists = null;

        String partnerId = memberGroupService.getPartnerId(memberId);
        boolean isBand = moneyManagementBizService.estimateWithdrawalPermissions(partnerId, memberId);
        MemberPartner memberPartner = memberPartnerService.findByMemberId(partnerId);
        MemberGroupInfo memberGroupInfo = memberGroupInfoService.findByMemberId(partnerId);

        Double withdrawalCharge_1 = 0d;
        if (null != memberGroupInfo) {
            withdrawalCharge_1 = memberGroupInfo.getWithdrawalCharge() == null ? 0d : BigDecimalUtils.mul(memberGroupInfo.getWithdrawalCharge(), 100);
        }


        if (StringUtils.isNotBlank(memberId)) {
            //众筹累计资金

            orderTotal = orderBizService.getOrderTotal(false, memberId, OrderType.ORDER_CROWD_FUND.getCode(), null);
            orderTotal = orderTotal == null ? 0d : orderTotal;

            //总可提现金额0
            totalAleAmount = 0d;
            totalAleAmount = memberWithdrawalFundService.getMemberCanWithdrawAmount(new MemberWithdrawalFund(memberId, null));
            totalAleAmount = totalAleAmount == null ? 0d : totalAleAmount;

            //已提现金额
            edWithdrawalsAmount = 0d;
            edWithdrawalsAmount = withdrawalsBizService.getWithdrawalTotal(memberId, Withdrawals.TYPE_CROWD_FUNDING, null);
            edWithdrawalsAmount = edWithdrawalsAmount == null ? 0d : edWithdrawalsAmount;

            //当前可提现金额
            ingWithdrawalsAmount = BigDecimalUtils.sub(totalAleAmount, edWithdrawalsAmount);

            cewoLists = memberWithdrawalFundService.getMemberEventWithdrawalList(memberId, page);
            for (CrowdfundEventWithdrawalsOutput cewoObj : cewoLists) {

                cewoObj.setEdWithdrawalsAmount(withdrawalsBizService.getWithdrawalTotal(memberId, Withdrawals.TYPE_CROWD_FUNDING, cewoObj.getId()));
                cewoObj.setIngWithdrawalsAmount(BigDecimalUtils.sub(cewoObj.getTotalAleAmount(), cewoObj.getEdWithdrawalsAmount()));

                //众筹付款
                ProjectAnalyze projectAnalyze = new ProjectAnalyze();
                projectAnalyze.setEventId(cewoObj.getId());
                projectAnalyze.setPayType(0);
                Double totalAmount = projectService.sumForActualAmount(projectAnalyze, 1);

                //直接付款
                ProjectAnalyze projectAnalyze_zj = new ProjectAnalyze();
                projectAnalyze_zj.setEventId(cewoObj.getId());
                projectAnalyze_zj.setPayType(1);
                Double totalAmount_zj = projectService.sumForActualAmount(projectAnalyze_zj, 0);

                totalAmount = BigDecimalUtils.add(totalAmount, totalAmount_zj);
                cewoObj.setOrderTotal(totalAmount);

            }
        }

        mv.addObject("orderTotal", orderTotal);
        mv.addObject("totalAleAmount", totalAleAmount);
        mv.addObject("edWithdrawalsAmount", edWithdrawalsAmount);
        mv.addObject("ingWithdrawalsAmount", ingWithdrawalsAmount);
        mv.addObject("cewoLists", cewoLists);
        mv.addObject("page", page);
        mv.addObject("memberPartner", memberPartner);
        mv.addObject("isBand", isBand);
        mv.addObject("memberId", memberId);


        mv.addObject("withdrawalCharge", withdrawalCharge_1);
        mv.addObject("memberName", memberGroupService.get(memberId).getRealname());
        mv.addObject("isChildAccount", memberGroupService.isChild(memberId));
        mv.addObject("partnerId", memberGroupService.getPartnerId(memberId));
        return mv;
    }


    /**
     * 资金管理 提现详情
     *
     * @return
     */
    @RequestMapping(value = "withdrawalInfo")
    public ModelAndView withdrawalInfo(Page page, String eventId, String memberId) {
        ModelAndView mv = new ModelAndView("moneyManagement/withdrawalInfo");
        page.setLimit(15);


        CrowdfundEvent ceObj = crowdfundEventService.get(eventId);
        if (null == ceObj) {
            return null;
        }
        String partnerId = memberGroupService.getPartnerId(memberId);
        MemberPartner memberPartner = memberPartnerService.findByMemberId(partnerId);
        MemberGroupInfo memberGroupInfo = memberGroupInfoService.findByMemberId(partnerId);


        Double withdrawalCharge_1 = 0d;
        if (null != memberGroupInfo) {
            withdrawalCharge_1 = memberGroupInfo.getWithdrawalCharge() == null ? 0d : BigDecimalUtils.mul(memberGroupInfo.getWithdrawalCharge(), 100);
        }

        int comp = DateUtils.compareDate(new Date(), ceObj.getEndTime());
        //众筹累计资金
        Double orderTotal = 0d;
        orderTotal = orderFormService.getOrderData(eventId, OrderStatus.ORDER_STATUS_HAVE_PAID.getCode(), null);
        orderTotal = orderTotal == null ? 0d : orderTotal;

        //总可提现金额
        Double totalAleAmount = 0d;
        totalAleAmount = memberWithdrawalFundService.getMemberCanWithdrawAmount(new MemberWithdrawalFund(memberId, eventId));
        totalAleAmount = totalAleAmount == null ? 0d : totalAleAmount;

        //已提现金额
        Double edWithdrawalsAmount = 0d;
        edWithdrawalsAmount = withdrawalsBizService.getWithdrawalTotal(memberId, Withdrawals.TYPE_CROWD_FUNDING, eventId);
        edWithdrawalsAmount = edWithdrawalsAmount == null ? 0d : edWithdrawalsAmount;

        //当前可提现金额
        Double ingWithdrawalsAmount = BigDecimalUtils.sub(totalAleAmount, edWithdrawalsAmount);

        Withdrawals withdrawal = new Withdrawals();
        withdrawal.setCreateBy(memberId);
        withdrawal.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        withdrawal.setType(Withdrawals.TYPE_CROWD_FUNDING);
        withdrawal.setBusinessId(eventId);
        List<Withdrawals> withdrawals = withdrawalService.listPage(withdrawal, page);
        List<WithdrawalOutput> withdrawalOutputs = LangUtils.transform(withdrawals, input -> {
            WithdrawalOutput output = WithdrawalOutput.transform(input);
            String account = input.getAccountNumber();
            account = withdrawalsBizService.formatAccountNumber(account);
            output.setAccountNumber(account);

            Double withdrawalCharge = input.getWithdrawalCharge();
            withdrawalCharge = withdrawalCharge == null ? 0d : withdrawalCharge;

            //提现金额X（平台提现手续费+微信提现手续费）
            double serviceFee = BigDecimalUtils.mul(input.getPayment(), Withdrawals.SERVER_FEE + withdrawalCharge);
            serviceFee = BigDecimalUtils.round(serviceFee, 2);
            // 净额
            double netAmount = BigDecimalUtils.sub(input.getPayment(), serviceFee);

            output.setServiceFee(serviceFee);
            output.setNetAmount(netAmount);
            return output;
        });
        mv.addObject("orderTotal", orderTotal);
        mv.addObject("totalAleAmount", totalAleAmount);
        mv.addObject("edWithdrawalsAmount", edWithdrawalsAmount);
        mv.addObject("ingWithdrawalsAmount", ingWithdrawalsAmount);
        mv.addObject("withdrawals", withdrawalOutputs);
        mv.addObject("ceObj", ceObj);
        mv.addObject("page", page);
        mv.addObject("finalPaymentOF", moneyManagementBizService.finalPayment(eventId,memberId));
        mv.addObject("asOFEventDate", comp == 1);
        mv.addObject(" withdrawalOF", moneyManagementBizService.estimateWithdrawalLog(memberId));
        mv.addObject("memberId", memberId);
        mv.addObject("memberPartner", memberPartner);
        mv.addObject("withdrawalCharge", withdrawalCharge_1);
        return mv;
    }

    /**
     * 获取机构提现信息
     *
     * @param eventId
     * @return
     */
    @ResponseBody
    @RequestMapping("getMemberWithdrawalInfo")
    public AjaxResult getMemberWithdrawalInfo(String eventId,String memberId) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            if (StringUtils.isBlank(eventId)) {
                logger.error("主题id为空", eventId);
                return AjaxResult.error("主题id为空");
            }

            //总可提现金额
            Double totalAleAmount = 0d;
            totalAleAmount = memberWithdrawalFundService.getMemberCanWithdrawAmount(new MemberWithdrawalFund(memberId, eventId));
            totalAleAmount = totalAleAmount == null ? 0d : totalAleAmount;

            //已提现金额
            Double edWithdrawalsAmount = 0d;
            edWithdrawalsAmount = withdrawalsBizService.getWithdrawalTotal(memberId, Withdrawals.TYPE_CROWD_FUNDING, eventId);
            edWithdrawalsAmount = edWithdrawalsAmount == null ? 0d : edWithdrawalsAmount;

            //当前可提现金额
            Double ingWithdrawalsAmount = BigDecimalUtils.sub(totalAleAmount, edWithdrawalsAmount);
            if (0d == ingWithdrawalsAmount) {
                ajaxResult.setDescription("当前可提现金额为0");
                return ajaxResult;
            }

            String partnerId = memberGroupService.getPartnerId(memberId);
            MemberBank memberBank = memberBankService.findByMemberId(partnerId);
            if (null == memberBank) {
                ajaxResult.setDescription("暂未添加银行卡,请联系管理员");
                return ajaxResult;
            }
            Double serviceFee = 0d;
            Double withdrawalCharge = 0d;

            MemberGroupInfo groupInfo = memberGroupInfoService.findByMemberId(partnerId);
            if (null != groupInfo) {
                withdrawalCharge = groupInfo.getWithdrawalCharge();
            }
            withdrawalCharge = withdrawalCharge == null ? 0d : withdrawalCharge;


            serviceFee = BigDecimalUtils.add(Withdrawals.SERVER_FEE, withdrawalCharge);
            Map<String, Object> mmp = new HashMap<>();
            mmp.put("ingWithdrawalsAmount", ingWithdrawalsAmount);
            mmp.put("memberBank", memberBank);
            mmp.put("serviceFee", serviceFee);
            mmp.put("memberId", memberId);
            return AjaxResult.success(mmp);
        } catch (Exception e) {
            logger.error("获取机构提现信息异常", e);
            return AjaxResult.error("获取提现信息异常");
        }
    }


    /**
     * 发起提现
     *
     * @param eventId
     * @param payment
     * @return
     */
    @ResponseBody
    @RequestMapping("initiateDrawings")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult initiateDrawings(String memberId,String eventId, double payment) {
        AjaxResult ajaxResult = new AjaxResult();
        try {

            //String memberId = RealmUtils.getCurrentUser().getId();

            if (payment <= 0d) {
                return AjaxResult.error("请输入0.01元以上的金额。");
            }

            //总可提现金额
            Double totalAleAmount = 0d;
            totalAleAmount = memberWithdrawalFundService.getMemberCanWithdrawAmount(new MemberWithdrawalFund(memberId, eventId));
            totalAleAmount = totalAleAmount == null ? 0d : totalAleAmount;

            //已提现金额
            Double edWithdrawalsAmount = 0d;
            edWithdrawalsAmount = withdrawalsBizService.getWithdrawalTotal(memberId, Withdrawals.TYPE_CROWD_FUNDING, eventId);
            edWithdrawalsAmount = edWithdrawalsAmount == null ? 0d : edWithdrawalsAmount;

            //当前可提现金额
            Double ingWithdrawalsAmount = BigDecimalUtils.sub(totalAleAmount, edWithdrawalsAmount);

            double sub = BigDecimalUtils.sub(ingWithdrawalsAmount, payment);
            if (sub < 0d) {
                return AjaxResult.error("当前可提现金额只有" + ingWithdrawalsAmount + "元。");
            }

            String partnerId = memberGroupService.getPartnerId(memberId);
            MemberBank memberBank = memberBankService.findByMemberId(partnerId);
            if (null == memberBank) {
                ajaxResult.setDescription("暂未添加银行卡,请联系管理员");
                return ajaxResult;
            }
            Double withdrawalCharge = 0d;

            MemberGroupInfo groupInfo = memberGroupInfoService.findByMemberId(partnerId);
            if (null != groupInfo) {
                withdrawalCharge = groupInfo.getWithdrawalCharge();
            }
            withdrawalCharge = withdrawalCharge == null ? 0d : withdrawalCharge;

            //                  提现金额X（平台提现手续费+微信提现手续费）
            double serviceFee = BigDecimalUtils.mul(payment, Withdrawals.SERVER_FEE + withdrawalCharge);

            serviceFee = BigDecimalUtils.round(serviceFee, 2);

            withdrawalsBizService.insertWithdrawal(memberBank, memberId, Withdrawals.TYPE_CROWD_FUNDING, (float) payment, eventId, serviceFee, withdrawalCharge);

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("发起提现异常", e);
            return AjaxResult.error("发起提现异常");
        }
    }

    /**
     * 尾款提现列表
     *
     * @param waoInput
     * @param page
     * @return
     */
    @RequestMapping(value = "tailParagraph/tailParagraphList")
    public ModelAndView tailParagraphList(WithdrawalAuditOperateInput waoInput, Page page, CommonInput input) {
        page.setLimit(20);
        ModelAndView modelAndView = new ModelAndView("moneyManagement/tailParagraphList");
        Map<String, Object> params = CommonInput.appendParams(input);
        params.put("progress", waoInput.getProgress());
        params.put("withdrawalMember", waoInput.getWithdrawalMember());
        params.put("name", waoInput.getName());

        if (null != params.get("startDate")) {
            input.setCreateStart(params.get("startDate").toString().substring(0, "2018-05-04".length()));
        }
        if (null != params.get("endDate")) {
            input.setCreateEnd(params.get("endDate").toString().substring(0, "2018-05-04".length()));
        }

        List<WithdrawalAuditOperateOutput> waoOutList = withdrawalAuditOperateService.queryTailParagraphList(Withdrawals.TYPE_TAIL_PARAGRAPH, params, page);

        modelAndView.addObject("list", waoOutList);
        modelAndView.addObject("page", page);
        modelAndView.addObject("input", input);
        modelAndView.addObject("waoInput", waoInput);
        return modelAndView;
    }


    /**
     * 尾款提现----发起提现
     *
     * @param eventId
     * @param noteMessage
     * @return
     */
    @ResponseBody
    @RequestMapping("tailParagraph/initiateDrawings")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult tailParagraphWithdrawal(String memberId,String eventId, String noteMessage) {
        AjaxResult ajaxResult = new AjaxResult();
        try {

            //String memberId = RealmUtils.getCurrentUser().getId();

            Withdrawals withdrawals = new Withdrawals();
            withdrawals.setCreateBy(memberId);
            withdrawals.setBusinessId(eventId);
            withdrawals.setType(Withdrawals.TYPE_TAIL_PARAGRAPH);

            Withdrawals queryWithdrawals = withdrawalService.queryWithdrawalsByDate(withdrawals, null);

            if (null != queryWithdrawals) {
                ajaxResult.setDescription("已经提交申请不可重复提交");
                return ajaxResult;
            }
            String partnerId = memberGroupService.getPartnerId(memberId);
            MemberBank memberBank = memberBankService.findByMemberId(partnerId);
            if (null == memberBank) {
                ajaxResult.setDescription("暂未添加银行卡,请联系管理员");
                return ajaxResult;
            }
            if (StringUtils.isNotBlank(noteMessage) && noteMessage.length() > 200) {
                ajaxResult.setDescription("备注信息不能大于200字");
                return ajaxResult;
            }
            String wid = withdrawalsBizService.insertWithdrawal(memberBank, memberId, Withdrawals.TYPE_TAIL_PARAGRAPH, 0f, eventId, 0d, 0d);
            WithdrawalAuditOperate w1 = new WithdrawalAuditOperate(wid, WithdrawalAuditOperate.PROGRESS_APPLY, noteMessage, WithdrawalAuditOperate.STATE_UNTREATED, Withdrawals.TYPE_TAIL_PARAGRAPH);
            w1.setCreateDate(new Date());
            WithdrawalAuditOperate w2 = new WithdrawalAuditOperate(wid, WithdrawalAuditOperate.PROGRESS_DEAL, "", WithdrawalAuditOperate.STATE_NOSTART, Withdrawals.TYPE_TAIL_PARAGRAPH);
            w2.setCreateDate(DateUtils.addOneSecond(new Date(), 1));
            withdrawalAuditOperateService.insert(w1);
            withdrawalAuditOperateService.insert(w2);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("发起提现异常", e);
            return AjaxResult.error("发起提现异常");
        }
    }


    /**
     * 尾款提现详情
     *
     * @param businessId
     * @return
     */
    @RequestMapping(value = "tailParagraph/tailParagraphInfo")
    public ModelAndView queryTailParagraphInfo(String businessId, String memberId) {
        ModelAndView modelAndView = new ModelAndView("moneyManagement/tailParagraphInfo");

        CrowdfundEvent event = null;
        List<WithdrawalAuditOperate> waoList = null;
        MemberGroup member = memberGroupService.get(memberId);

        if (StringUtils.isNotBlank(businessId) && null != member) {

            event = crowdfundEventService.get(businessId);
            waoList = withdrawalAuditOperateService.queryTailParagraphInfo(businessId, memberId);
        }
        ;

        modelAndView.addObject("list", waoList);
        modelAndView.addObject("event", event);
        modelAndView.addObject("businessId", businessId);
        modelAndView.addObject("memberId", memberId);
        return modelAndView;
    }

    /**
     * 编辑尾款提现
     *
     * @param input
     * @return
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "tailParagraph/editTailParagraph")
    public AjaxResult editTailParagraph(WithdrawalAuditOperateInput input) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            Withdrawals withdrawals = withdrawalService.get(input.getwId());
            WithdrawalAuditOperate withdrawalAuditOperate = withdrawalAuditOperateService.get(input.getId());
            if (null == withdrawals || withdrawalAuditOperate == null) {
                throw new BusinessException(555, "提现id为空");
            }

            //客服处理
            if (WithdrawalAuditOperate.PROGRESS_DEAL == input.getProgress()) {
                //通过
                if (WithdrawalAuditOperate.PROGRESS_APPLY == input.getState()) {
                    if (input.getPayment() < 0.01f) {
                        throw new BusinessException(555, "提现金额不能少于0.01");
                    }
                    Double orderTotal = 0d;
                    orderTotal = orderFormService.getOrderData(withdrawals.getBusinessId(), OrderStatus.ORDER_STATUS_HAVE_PAID.getCode(), null);
                    orderTotal = orderTotal == null ? 0d : orderTotal;

                    Float orderTotalf = orderTotal.floatValue();
                    if (input.getPayment() > orderTotalf) {
                        throw new BusinessException(555, "提现金额不能大于累计资金");
                    }
                    withdrawals.setPayment(input.getPayment());
                    withdrawalAuditOperate.setPayment(input.getPayment());
                    withdrawalAuditOperate.setAccessoryUrl(input.getAccessoryUrl());
                }
            }

            withdrawals.setProgress(input.getProgress());
            withdrawalService.update(withdrawals);


            withdrawalAuditOperate.setNoteMessage(input.getNoteMessage());
            withdrawalAuditOperate.setState(input.getState());

            withdrawalAuditOperateService.update(withdrawalAuditOperate);

            if (WithdrawalAuditOperate.PROGRESS_REMITTANCE != input.getProgress()) {
                if (WithdrawalAuditOperate.STATE_UNTREATED == input.getState()) {
                    withdrawalAuditOperateService.insert(new WithdrawalAuditOperate(withdrawals.getId(), input.getProgress() + 1, "", WithdrawalAuditOperate.STATE_NOSTART, Withdrawals.TYPE_TAIL_PARAGRAPH));
                }
                if (WithdrawalAuditOperate.STATE_PROCESSED == input.getState()) {
                    withdrawalAuditOperateService.insert(new WithdrawalAuditOperate(withdrawals.getId(), WithdrawalAuditOperate.PROGRESS_CONFIRM, "", WithdrawalAuditOperate.STATE_NOSTART, Withdrawals.TYPE_TAIL_PARAGRAPH));
                }
            }
        } catch (BusinessException be) {
            logger.error("编辑尾款提现异常", be);
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("编辑尾款提现异常", e);
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("编辑尾款提现异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }


    /**
     * 上传附件
     *
     * @param id
     * @param accessoryUrl
     * @return
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "tailParagraph/uploadccessory")
    public AjaxResult editTailParagraph(String id, String accessoryUrl) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            WithdrawalAuditOperate withdrawalAuditOperate = withdrawalAuditOperateService.get(id);
            if (withdrawalAuditOperate == null) {
                throw new BusinessException(555, "提现id为空");
            }
            if (StringUtils.isBlank(accessoryUrl)) {
                throw new BusinessException(555, "附件路径为空");
            }
            withdrawalAuditOperate.setAccessoryUrl(accessoryUrl);
            withdrawalAuditOperateService.update(withdrawalAuditOperate);
        } catch (BusinessException be) {
            logger.error("上传附件异常", be);
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("上传附件异常", e);
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("上传附件异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }
}
